package com.heo.thread;

import org.apache.log4j.Logger;
import com.heo.util.NettyChannelMapUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

public class SendMessageTransparentThread implements Runnable {

	private static Logger logger = Logger.getLogger(SendMessageTransparentThread.class);

	private String sendJson;
	private int sleep = 100;
	private Channel channel = null;
	private String deviceImei = "";

	public SendMessageTransparentThread(String appId, String deviceImei, String sendJson, int sleep) {
		this.channel = NettyChannelMapUtils.get(appId, deviceImei);
		this.sendJson = sendJson;
		this.sleep = sleep;
		this.deviceImei = deviceImei;
	}

	@Override
	public void run() {
		try {
			if (channel != null) {
				if(sleep > 0) {
					Thread.sleep(sleep);
				}
				if(channel.isActive() && channel.isWritable()) {
					channel.writeAndFlush(sendJson + "\n").addListener(new ChannelFutureListener() {
						@Override
					    public void operationComplete(ChannelFuture future) throws Exception {
					    	logger.info(deviceImei + "" + sendJson + "消息发送结果=" + future.isSuccess());
					    }
					});
				}
			}
		} catch (Exception e) {
			logger.info("SendMessageTransparentThread Exception = " + e.getMessage());
		}
	}
}
